<script setup lang="tsx">
import { regionsListRegionApi } from '@/api/regions'
import { Province } from '@/api/regions/types'
import { businessListApi } from '@/api/merchantManagement'
import type { businessListParams } from '@/api/merchantManagement/types'
import Write from './components/Write.vue'
import Detail from './components/Detail.vue'
import { ElButton } from 'element-plus'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useI18n } from '@/hooks/web/useI18n'
import { useTable } from '@/hooks/web/useTable'
import { useSearch } from '@/hooks/web/useSearch'
// import { BusinessStateDict, CompanyTypeDict, dictToList } from '@/utils/dict'
import { CompanyTypeDict, MemberStateDict, dictToList, FinancialTypeDict } from '@/utils/dict'
import { useRouter } from 'vue-router'

const { t } = useI18n()

const { push } = useRouter()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const res = await businessListApi({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.data.list || [],
      total: res.data.total || 0
    }
  }
})
const { total, loading, dataList, pageSize, currentPage } = tableState
const { getList } = tableMethods

const { searchRegister, searchMethods } = useSearch()
const { setValues } = searchMethods

const isDisabled = ref(true)
const parentId = ref(0)
const provinceList = ref<Province[]>([])
const cityList = ref<Province[]>([])

const getProvinceList = async () => {
  const res = await regionsListRegionApi(0)
  provinceList.value = res.data
  return res.data?.map((v) => ({
    label: v.localName,
    value: v.id
  }))
}

getProvinceList()

const getCityList = async (id) => {
  const res = await regionsListRegionApi(id)
  cityList.value = res.data
  return res.data?.map((v) => ({
    label: v.localName,
    value: v.id
  }))
}

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'id',
    label: '商家ID',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'businessNo',
    label: '商家ID',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'businessShortName',
    label: '商家简称',
    search: {
      componentProps: {
        placeholder: '请输入商家简称'
      }
    },
    form: {
      hidden: true
    },
    table: {
      width: 220,
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <div class={'flex items-center'}>
                <img class={'w-10 mr-3'} src={row.logo} />
                <span>{row.businessShortName}</span>
              </div>
            </>
          )
        }
      }
    }
  },
  {
    field: 'hfMerchantNo',
    label: '汇付商户号',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      width: 100
    }
  },
  {
    field: 'contactName',
    label: '联系人',
    search: {
      componentProps: {
        placeholder: '请输入联系人姓名/手机号'
      }
    },
    form: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <div>{row.contactMobileNo}</div>
              <div>{row.contactName}</div>
            </>
          )
        }
      }
    }
  },
  {
    field: 'businessName',
    label: '企业名称',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'provinceId',
    label: '省',
    search: {
      component: 'Select',
      componentProps: {
        on: {
          change: (val: number) => {
            console.log(val)
            if (val) {
              isDisabled.value = false
              parentId.value = val
              setValues({
                cityId: null
              })
            } else {
              isDisabled.value = true
              setValues({
                cityId: null
              })
            }
          }
        }
      },
      optionApi: async () => getProvinceList()
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'cityId',
    label: '市',
    search: {
      component: 'Select',
      componentProps: {
        disabled: isDisabled
      },
      optionApi: async () => getCityList(parentId.value)
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'provinceName',
    label: '所属省市',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <span>
                {row.provinceName}
                {row.cityName}
              </span>
            </>
          )
        }
      }
    }
  },
  {
    field: 'position',
    label: '详细地址',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'memberState',
    label: '会员状态',
    form: {
      hidden: true
    },
    search: {
      component: 'Select',
      componentProps: {
        options: dictToList(MemberStateDict)
      }
    },
    table: {
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <span>{row.memberState && MemberStateDict[row.memberState]}</span>
            </>
          )
        }
      }
    }
  },
  // {
  //   field: 'state',
  //   label: t('userDemo.status'),
  //   form: {
  //     hidden: true
  //   },
  //   search: {
  //     component: 'Select',
  //     componentProps: {
  //       options: dictToList(BusinessStateDict)
  //     }
  //   },
  //   table: {
  //     slots: {
  //       default: (data: any) => {
  //         const row = data.row as any
  //         return (
  //           <>
  //             <span>{row.state && BusinessStateDict[row.state]}</span>
  //           </>
  //         )
  //       }
  //     }
  //   }
  // },
  {
    field: 'companyType',
    label: '商家类型',
    form: {
      hidden: true
    },
    search: {
      component: 'Select',
      componentProps: {
        options: dictToList(CompanyTypeDict)
      }
    },
    table: {
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <span>{row.companyType && CompanyTypeDict[row.companyType]}</span>
            </>
          )
        }
      }
    }
  },
  {
    field: 'financialAccountType',
    label: '结算类型',
    form: {
      hidden: true
    },
    search: {
      component: 'Select',
      componentProps: {
        options: dictToList(FinancialTypeDict)
      }
    },
    table: {
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <span>{row.financialAccountType && FinancialTypeDict[row.financialAccountType]}</span>
            </>
          )
        }
      }
    }
  },
  {
    field: 'remainActiveCount',
    label: '剩余发布次数',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      width: 100
    }
  },
  {
    field: 'buyCardCount',
    label: '会员权益',
    form: {
      hidden: true
    },
    search: {
      hidden: true
    },
    table: {
      width: 120,
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <div>
                经纪人：{row.agentCount}/
                {!row.maxInviteAgentCount ? '不限' : row.maxInviteAgentCount}
              </div>
              <div>
                活动商户：
                {!row.singleActiveMerchantCount ? '不限' : row.singleActiveMerchantCount + '家'}
              </div>
            </>
          )
        }
      }
    }
  },
  {
    field: 'buyCardCount',
    label: '累计购卡',
    form: {
      hidden: true
    },
    search: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <div>{row.buyCardCount}次</div>
              <div>{row.buyCardAmt}</div>
            </>
          )
        }
      }
    }
  },
  {
    field: 'buyCardCount',
    label: '累计会员续费',
    form: {
      hidden: true
    },
    search: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <div>{row.memberFeeCount}次</div>
              <div>{row.memberFeeAmt}</div>
            </>
          )
        }
      }
    }
  },
  {
    field: 'createTime',
    label: '入驻时间',
    search: {
      component: 'DatePicker',
      componentProps: {
        type: 'datetimerange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    },
    form: {
      hidden: true
    },
    table: {
      width: 220
    }
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    search: {
      hidden: true
    },
    table: {
      width: 250,
      slots: {
        default: (data: any) => {
          const row = data.row as businessListParams
          return (
            <>
              <ElButton
                v-hasPermi="GET /business/details"
                type="primary"
                link
                onClick={() => details(row)}
              >
                查看详情
              </ElButton>
              <ElButton type="primary" link onClick={() => business(row)}>
                关联商户
              </ElButton>
              <ElButton type="primary" link onClick={() => agent(row)}>
                关联经纪人
              </ElButton>
            </>
          )
        }
      }
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const searchParams = ref({})
const setSearchParams = (params: any) => {
  const { createTime, provinceId, cityId, ...rest } = params
  let startTime, endTime, cityName, provinceName
  if (createTime && createTime.length > 0) {
    startTime = createTime[0]
    endTime = createTime[1]
  }
  if (provinceId) {
    provinceName = provinceList.value.find((item) => item.id === provinceId)?.localName
  }
  if (cityId) {
    cityName = cityList.value.find((item) => item.id === cityId)?.localName
  }
  currentPage.value = 1
  if (Object.keys(params).length === 0) {
    isDisabled.value = true
  }
  searchParams.value = {
    startTime,
    endTime,
    cityName,
    provinceName,
    ...rest
  }
  getList()
}

const showDrawer = ref(false)

const business = (row) => {
  push(`/merchantManagement/detail?id=${row.id}`)
}
const agent = (row) => {
  push(`/agent/list?id=${row.id}`)
}

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref<businessListParams>()
// const actionType = ref('')

// const AddAction = () => {
//   dialogTitle.value = t('exampleDemo.add')
//   currentRow.value = undefined
//   dialogVisible.value = true
//   allSchemas.formSchema.at(1)!.hidden = false
//   actionType.value = ''
// }

// const delLoading = ref(false)
// const ids = ref<number[]>([])

const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)

const save = async () => {
  saveLoading.value = true
  const write = unref(writeRef)
  const res = await write?.submit()
  saveLoading.value = false
  if (!res) {
    return
  }
  dialogVisible.value = false
  getList()
}

const detail = ref()

const details = async (row: any) => {
  detail.value = row
  showDrawer.value = true
}
</script>

<template>
  <div class="flex w-100% h-100%">
    <ContentWrap class="flex-[3] ml-20px">
      <Search
        :schema="allSchemas.searchSchema"
        @reset="setSearchParams"
        @search="setSearchParams"
        @register="searchRegister"
      />

      <!-- <div class="mb-10px">
        <ElButton v-hasPermi="'POST /admin/user/create'" type="primary" @click="AddAction">{{
          t('exampleDemo.add')
        }}</ElButton>
      </div> -->
      <Table
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :columns="allSchemas.tableColumns"
        :data="dataList"
        :loading="loading"
        @register="tableRegister"
        :pagination="{
          total
        }"
      />
    </ContentWrap>

    <ElDrawer v-model="dialogVisible" :title="dialogTitle" size="650px">
      <Write ref="writeRef" :form-schema="allSchemas.formSchema" :current-row="currentRow" />

      <template #footer>
        <ElButton type="primary" :loading="saveLoading" @click="save">
          {{ t('exampleDemo.save') }}
        </ElButton>
        <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
      </template>
    </ElDrawer>

    <ElDrawer title="商家详情" v-model="showDrawer" direction="rtl" size="650px" @close="getList">
      <Detail v-if="showDrawer" :detailObj="detail" />
    </ElDrawer>
  </div>
</template>
